package com.tankgame4;

import java.io.*;
import java.util.Vector;

/**
 * 该类用于记录相关信息和文件交互
 */
public class Recorder {
    // 记录我方击毁敌人坦克数
    private static int allEnemyTankNum = 0;
    // 定义IO对象，写数据至文件中
    private static FileWriter fw = null;
    private static BufferedWriter bw = null;
    private static BufferedReader br = null;
    private static String recordFile = "D:\\Code\\HanShunPing\\src\\myRecord.txt";

    // 定义一个Node的vector 用于保存敌人的信息
    private static Vector<Node> nodes = new Vector<>();

    // 定义Vector， 指向MyPanel的敌人坦克的Vector
    private static Vector<EnemyTank> enemyTanks = null;

    // 从文件读取敌方坦克位置信息， 并用此信息初始化敌方坦克位置
    public static Vector<Node> getNodesAndEnemyTankRec() {
        try {
            br = new BufferedReader(new FileReader(recordFile));
            allEnemyTankNum = Integer.parseInt(br.readLine());
            // 读取文件每行信息 生成nodes集合
            String line = "";
            while ((line = br.readLine()) != null) {
                String[] xyd = line.split(" ");
                Node node = new Node(Integer.parseInt(xyd[0]), Integer.parseInt(xyd[1]), Integer.parseInt(xyd[2]));
                nodes.add(node);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if (br != null) {
                    br.close();
                }

            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return nodes;
    }

    public static void setEnemyTanks(Vector<EnemyTank> enemyTanks) {
        Recorder.enemyTanks = enemyTanks;
    }

    public static int getAllEnemyTankNum() {
        return allEnemyTankNum;
    }

    public static void setAllEnemyTankNum(int allEnemyTankNum) {
        Recorder.allEnemyTankNum = allEnemyTankNum;
    }

    // 当我方坦克每击毁敌人
    public static void addAllEnemyTankNum() {
        Recorder.allEnemyTankNum++;
    }

    // 当退出时 将allEnemyTankNum保存到"d:\\myRecord.txt"
    public static void keepRecord() {
        try {
            bw = new BufferedWriter(new FileWriter(recordFile));
            bw.write(allEnemyTankNum + "\r\n");
            // 遍历敌人坦克的Vector 获取各对象的坐标信息 并写入文件
            for (int i = 0; i < enemyTanks.size(); i++) {
                EnemyTank enemyTank = enemyTanks.get(i);
                if (enemyTank.isLive) {
                    String record = enemyTank.getX() + " " + enemyTank.getY() + " " + enemyTank.getDirect();
                    bw.write(record + "\r\n");
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if (bw != null) {
                    bw.close();
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
